<?php
	require_once( "functions/inc_systemFunctions.php" );
	
	#check if the current user already has a shopping-list
	$sql = "SELECT id FROM shoppingList WHERE userData_id = " . $_SESSION['user_id'];
	$res = mysql_query( $sql );
	$now = date( "Y-m-d H:i:s" );
	if( mysql_num_rows( $res ) == 0 ){
		$sql_addShoppingList = "INSERT INTO shoppingList (title, userData_id, isActive, lastWriteAccess) VALUES ('Shopping-List of " . $_SESSION['firstName'] . " " . $_SESSION['lastName'] . "', '" . $_SESSION['user_id'] . "', 1, '" . $now . "')";
		$res_addShoppingList = mysql_query( $sql_addShoppingList );
		if( !$res_addShoppingList ) echo mysql_error();
		$lastId = mysql_insert_id();
	}
	
	#check if item is already in current users' shopping list
	$sql_checkItem = "SELECT * FROM shoppingListItems WHERE shoppingList_id = '" . getShoppingListId( $_SESSION['user_id'] ) . "' AND product_id = '" . $_GET['pid'] . "'";
	$res_checkItem = mysql_query( $sql_checkItem );
	if( !$res_checkItem ){
		echo mysql_error();
	}
	if( mysql_num_rows( $res_checkItem ) == 0 ){
		#save product to shoppingList
		$sql_addItem = "INSERT INTO shoppingListItems (product_id, shoppingList_id, seenInStore, lastWriteAccess) VALUES (" . $_GET['pid'] . ", " . getShoppingListId( $_SESSION['user_id'] ) . ", 0, '" . $now . "')";
		$res_addItem = mysql_query( $sql_addItem );
		if( !$res_addItem ){
			echo mysql_error();
		} else {
			header( "Location: " . $_SERVER['HTTP_REFERER'] );
		}
	} elseif( mysql_num_rows( $res_checkItem ) > 0 ){
		$row_checkItem = mysql_fetch_array( $res_checkItem );
		if( $row_checkItem['seenInStore'] == 1 ){
			$sql_updateSeen = "UPDATE shoppingListItems SET seenInStore = 0, lastWriteAccess = '" . $now . "' WHERE id = " . $row_checkItem['id'];
			$res_updateeen = mysql_query( $sql_updateSeen );
			if( !$res_updateeen ){
				echo mysql_error();
			} else {
				header( "Location: " . $_SERVER['HTTP_REFERER'] );
			}
		}
	}
?>